package org.aplikator.client.shared.rpc.marshaller;

import org.aplikator.client.shared.descriptor.EntityDTO;
import org.aplikator.client.shared.descriptor.PropertyDTO;
import org.jboss.errai.marshalling.client.api.Marshaller;
import org.jboss.errai.marshalling.client.api.MarshallingSession;
import org.jboss.errai.marshalling.client.api.annotations.ClientMarshaller;
import org.jboss.errai.marshalling.client.api.annotations.ServerMarshaller;
import org.jboss.errai.marshalling.client.api.json.EJObject;
import org.jboss.errai.marshalling.client.api.json.EJValue;
import org.jboss.errai.marshalling.client.marshallers.AbstractNullableMarshaller;

@ClientMarshaller(EntityDTO.class)
@ServerMarshaller(EntityDTO.class)
public class EntityDTOMarshaller extends AbstractNullableMarshaller<EntityDTO> {

	/*@Override
	public Class<EntityDTO> getTypeHandled() {
		return EntityDTO.class;
	}*/

	@Override
	public EntityDTO[] getEmptyArray() {
		return new EntityDTO[0];
	}

	@Override
	public EntityDTO doNotNullDemarshall(EJValue o, MarshallingSession ctx) {
		if (o.isObject() != null) {
			EJObject ejObject = o.isObject();
			EntityDTO edto = new EntityDTO();
			DemarshallingUtils.clientDescriptorBaseUnMarshall(ejObject, edto);
			Marshaller<Object> marsh = ctx
					.getMarshallerInstance(PropertyDTO.class.getName());
			PropertyDTO pk = (PropertyDTO) marsh.demarshall(
					ejObject.get("primaryKey"), ctx);
			edto.setPrimaryKey(pk);
			if (ejObject.containsKey("indexed")) {
				edto.setIndexed(ejObject.get("indexed").isBoolean()
						.booleanValue());
			}
			return edto;
		} else
			return null;
	}

	@Override
	public String doNotNullMarshall(EntityDTO o, MarshallingSession ctx) {
		StringBuilder builder = new StringBuilder().append('{');
		MarshallingUtils.clientDescriptorBase(builder, o).append(',');
		MarshallingUtils.key("primaryKey", builder).append(':');
		Marshaller<Object> marsh = ctx.getMarshallerInstance(PropertyDTO.class
				.getName());
		builder.append(marsh.marshall(o.getPrimaryKey(), ctx)).append(',');
		MarshallingUtils.bool("indexed", o.isIndexed(), builder);
		builder.append('}');
		return builder.toString();
	}
}
